package com.szholly.plug.form.excel.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.szholly.utils.common.web.IRealPathResolver;
import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.utils.util.StringUtils;
import com.szholly.plug.form.excel.web.interceptor.ExcelInterceptorRegister;
import com.szholly.plug.form.excel.web.interceptor.IExcelInterceptor;
import com.szholly.plug.form.upload.UploadPara;

@Controller
public class ExcelUploadController {
	@Autowired
	private IRealPathResolver realPathResolver;

	@SuppressWarnings({ "unchecked" })
	@RequestMapping(value = "/excelplupload/upload.do")
	@ResponseBody
	public void fileUpload(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("excelid") String excelid) throws ServletException, IOException {

		UploadPara uploadPara = (UploadPara) SpringBeanFactory
				.getBean("uploadPara");
		String uploadPath = uploadPara.getUploadPath();
		String savePath = null;
		String saveUrl = null;
		String repositoryPath = null;
		if (StringUtils.IsNullOrSpace(uploadPath)) {
			uploadPath = "temp/upload/";
		}
		uploadPath += "plupload/";
		savePath = realPathResolver.get("/") + uploadPath;
		repositoryPath = savePath + "temp/";
		saveUrl = request.getContextPath() + "/" + uploadPath;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";

		File dirFile = new File(repositoryPath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		response.setCharacterEncoding("UTF-8");
		Integer schunk = null;// 分割块数
		Integer schunks = null;// 总分割数
		String name = null;// 文件名
		BufferedOutputStream outputStream = null;
		if (ServletFileUpload.isMultipartContent(request)) {
			try {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold(1024);
				factory.setRepository(new File(repositoryPath));// 设置临时目录
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("UTF-8");
				upload.setSizeMax(100 * 1024 * 1024);// 设置附近大小
				List<FileItem> items = upload.parseRequest(request);
				// 生成新文件名
				String newFileName = null;
				for (FileItem item : items) {
					if (!item.isFormField()) {// 如果是文件类型
						name = item.getName();// 获得文件名
						newFileName = UUID.randomUUID().toString()
								.replace("-", "").concat(".")
								.concat(FilenameUtils.getExtension(name));
						if (name != null) {
							String nFname = newFileName;
							if (schunk != null) {
								nFname = schunk + "_" + name;
							}
							File savedFile = new File(savePath, nFname);
							item.write(savedFile);
						}
					} else {
						// 判断是否带分割信息
						if (item.getFieldName().equals("chunk")) {
							schunk = Integer.parseInt(item.getString());
						}
						if (item.getFieldName().equals("chunks")) {
							schunks = Integer.parseInt(item.getString());
						}
					}
				}

				if (schunk != null && schunk + 1 == schunks) {
					outputStream = new BufferedOutputStream(
							new FileOutputStream(
									new File(savePath, newFileName)));
					// 遍历文件合并
					for (int i = 0; i < schunks; i++) {
						File tempFile = new File(savePath, i + "_" + name);
						byte[] bytes = FileUtils.readFileToByteArray(tempFile);
						outputStream.write(bytes);
						outputStream.flush();
						tempFile.delete();
					}
					outputStream.flush();
				}

				String result = impExcel(excelid,savePath + newFileName);
				if(StringUtils.IsNullOrSpace(result)){
					result= "{}";
				}
				// 将Excel导入的结果，放到resultObject中，带到前台去
				response.getWriter().write(
						"{\"status\":true,\"newName\":\"" + saveUrl
								+ newFileName + "\", \"resultObject\":"+result+"}");
			} catch (FileUploadException e) {
				e.printStackTrace();
				response.getWriter().write("{\"status\":false}");
			} catch (Exception e) {
				e.printStackTrace();
				response.getWriter().write("{\"status\":false}");
			} finally {
				try {
					if (outputStream != null)
						outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 编辑操作前
	 */
	public static String impExcel(String excelId, String excelFile) {
		for (IExcelInterceptor editItem : ExcelInterceptorRegister.excelInterceptor) {
			if (editItem != null && editItem.getExcelId().equals(excelId)) {
				String returnString = editItem.impExcel(excelFile);
				if(!StringUtils.IsNullOrSpace(returnString)){
					return returnString;
				}
			}
		}
		return null;
	}
}